package xyz.hujf.tool.并发包原理解析.抽象同步队列;

import java.util.ArrayList;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantReadWriteLock;

/**
 * @author Hujf
 * @title: ReetrantWRLock
 * @date 2021-04-30 13:30
 * @description:
 * ReentrantReadWriteLock 巧妙地使
 * 用 state 的高 16 位表示读状态，也就是获取到读锁的次数；使用低 16 位表示获取到写锁
 * 的线程的可重入次数 。
 */
public class ReetrantWRLock {

    private ReentrantReadWriteLock lock = new ReentrantReadWriteLock();

    private ArrayList <String>array = new ArrayList<>();

    private final Lock readLock = lock.readLock();
    private final Lock writeLock = lock.writeLock();

    public void add(String e){
        writeLock.lock();
        try {
            array.add(e);
        }finally {
            writeLock.unlock();
        }
    }

    public void remove(String e){
        writeLock.lock();
        try {
            array.remove(e);
        }finally {
            writeLock.unlock();
        }
    }

    public void get(int index ){
        readLock.lock();
        try {
            array.get(index);
        }finally {
            readLock.unlock();
        }
    }





    public static void main(String[] args) throws InterruptedException {
       // ArrayList arrayList = new ArrayList();
        ReetrantWRLock arrayList = new ReetrantWRLock();
        Thread t1 =new Thread(()->{
            for(int i=0;i<1000;i++){
                arrayList.add(i+"");
            }
        });
        Thread t2 =new Thread(()->{
            for(int i=0;i<1000;i++){
                arrayList.add(i+"");
            }
        });
        t1.start();
        t2.start();

        t1.join();
        t2.join();
        System.out.println(arrayList.size());
    }

    private int size() {
        return array.size();
    }
}
